from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from app.api import auth, users, departments, employees
from fastapi.middleware.cors import CORSMiddleware
import os

from app.core.database import get_db
from app.core.security import create_access_token, verify_password
from app.models.user import User
from app.api import users

app = FastAPI(
    title="人员管理系统",
    description="基于 FastAPI 的人员管理系统",
    version="1.0.0",
    docs_url=None  # 禁用默认的 Swagger UI
)

# 添加模板支持
templates = Jinja2Templates(directory="templates")

# OAuth2 配置
oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="api/auth/login",
    description="请输入用户名和密码进行认证"
)

# CORS设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 静态文件配置
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    """返回登录页面"""
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/docs", response_class=HTMLResponse)
async def custom_docs(request: Request):
    """返回自定义的文档页面"""
    return templates.TemplateResponse("docs.html", {"request": request})

@app.post("/api/auth/login")
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(),
    db: Session = Depends(get_db)
):
    """处理登录请求"""
    # 查找用户
    user = db.query(User).filter(User.username == form_data.username).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    # 验证密码
    if not verify_password(form_data.password, user.password_hash):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    # 检查用户状态
    if user.status != 1:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户已被禁用"
        )
    
    # 生成访问令牌
    access_token = create_access_token(data={"sub": user.username})
    
    # 返回更多用户信息
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "username": user.username,  # 确保返回用户名
        "role_id": user.role_id     # 确保返回角色ID
    }

# 添加路由
from app.api import auth, employees, departments, roles
app.include_router(auth.router, prefix="/api/auth", tags=["用户认证"])
app.include_router(employees.router, prefix="/api/employees", tags=["员工管理"])
app.include_router(departments.router, prefix="/api/departments", tags=["部门管理"])
app.include_router(roles.router, prefix="/api/roles", tags=["角色管理"])
app.include_router(users.router, prefix="/api/users", tags=["用户管理"])

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)